<div class="layui-tab-item layui-show" style="padding: 20px;">
    <div class="">
        <div id="layui-card">
            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
                <legend>已选标签</legend>
            </fieldset>
            <div class="layui-form">
                <div class="layui-form-item" id="select_label">
                    {empty name="labels"}
                    所选商品暂无标签
                    {/empty}
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    //渲染表单
    layui.use('form', function () {
        var form = layui.form;
        form.render();
    });
    var selected = new Array;

    var labels = eval("("+'{$labels|raw}'+")");
    if(labels.length>0){
        $.each(labels,function (i,j) {
            appendLabel(j.name, j.style);
        })
    }

    //删除标签
    $(".layui-layer-content").on('click','.layui-unselect',function () {
        var label = $(this).parent().parent();
        var label_text = label.attr('data-text');
        if(selected.length>0){
            $.each(selected, function (i, j) {
                if(selected[i]){
                    if (j.text == label_text) {
                        selected.splice(i, 1);
                        label.remove();
                    }
                }
            });
        }
    });
    //追加标签
    function appendLabel(label_text, label_style) {
        var current = {'text': label_text, 'style': label_style};
        var isAppend = true;
        $.each(selected, function (i, j) {
            if (j.text == label_text) {
                layer.msg(label_text + '标签已存在');
                isAppend = false;
                return false;
            }
        });
        if (isAppend) {
            selected.push(current);
            switch (label_style) {
                case 'red':
                    label_style = "";
                    break;
                case 'green':
                    label_style = "layui-bg-green";
                    break;
                case 'orange':
                    label_style = "layui-bg-orange";
                    break;
                case 'blue':
                    label_style = "layui-bg-blue";
                    break;
                default :
                    label_style = '';
            }
            var html = '<div class="layui-inline" data-text="'+label_text+'"><label class="layui-form-label"><span class="layui-badge ' + label_style + '" >' + label_text + '</span><i class="layui-icon layui-unselect layui-tab-close">ဆ</i></label></div>';
            $("#select_label").append(html);
        }
    }

    function getSelected() {
        if(selected<=0){
            return [];
        }
        return selected;
    }
</script>
